﻿using System;
using System.Collections.Concurrent;
using log4net;

namespace Hjt212Parser
{
    public class MyCounter
    {
        private static readonly ConcurrentDictionary<string, int> AllCounters = new ConcurrentDictionary<string, int>();
        private static readonly ILog Log = LogManager.GetLogger(typeof(MyCounter));

        /// <summary>
        /// 特制定时器，专门为信息缓冲使用。
        /// </summary>
        /// <param name="methodName">一般为方法名称</param>
        /// <param name="max">最大次数</param>
        /// <returns></returns>
        public static bool IsToTheMax(string methodName, int max)
        {
            try
            {              
                if (!AllCounters.ContainsKey(methodName))
                {
                    AllCounters.TryAdd(methodName, 1);
                    return false;
                }

                AllCounters.TryRemove(methodName, out var before);
                if (before > max)
                {                   
                    AllCounters.TryAdd(methodName, 0);
                    return true;
                }

                AllCounters.TryAdd(methodName, ++before);

            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            return false;
        }
        public static void UpdateToZero(string methodName)
        {
            try
            {               
                if (AllCounters.ContainsKey(methodName))
                {
                    AllCounters.TryRemove(methodName, out _);
                    AllCounters.TryAdd(methodName, 0);
                } 
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
        public static void Remove(string methodName)
        {
            try
            {               
                if (AllCounters.ContainsKey(methodName))
                {
                    AllCounters.TryRemove(methodName, out _);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

    }
}
